<template>
  <!--  {{ mainPageStore.data.length }}-->
  <avue-form :option="option" v-model="formData"
             @submit="submit"
  ></avue-form>
</template>
<script>
import {useMainPageStore} from "@/store/mainPageStore";
import pinia from "@/store/store";
import {isValidArray} from "element-plus/es/components/tree-select/src/utils";


import _ from 'lodash';
import {
  getAppConfig,
  processAppConfig,
  processColumn,
  processExamHallDict,
  processExportColumnDicData,
  processNamePropNameMap, TEST_ARRANGE_APP_CONFIG_KEY
} from "@/util/appConfigUtil";
import {SessionUtils} from "@/util/sessionUtils";

const appConfig = getAppConfig()
const mainPageStore = useMainPageStore(pinia)


export default {
  name: "CourseSettingForm",
  data() {
    return {
      formData: {},

      option: {
        submitText: "保存",
        emptyBtn: false,
        menuBtn: true,
        tabs: true,
        group: [
          {
            icon: 'el-icon-info',
            label: 'SETP1:学科设置',
            prop: 'group0',
            column: [
              {
                label: '考试科目',
                prop: 'subjects',
                type: 'dynamic',
                children: {
                  index: false,
                  indexLabel: "序号",
                  align: 'center',
                  type: 'form',
                  headerAlign: 'left',
                  rowAdd: (done) => {
                    this.$message.success('新增回调');
                    done({
                      input: '默认值'
                    });
                  },
                  rowDel: (row, done) => {
                    this.$message.success('删除回调' + JSON.stringify(row));
                    done();
                  },
                  column: [
                    {
                      label: '科目',
                      prop: "subjectName",
                      type: 'input',
                      span: 14,
                    },
                    {
                      label: '课程编码',
                      prop: "subjectCode",
                      type: 'input',
                      span: 10
                    }
                  ]
                },
              }]
          },
          {
            icon: 'el-icon-info',
            label: 'SETP2:校区配置',
            prop: 'group1',
            column:
                [
                  {
                    labelWidth: 120,
                    label: '',
                    prop: 'campus',
                    type: 'dynamic',
                    span: 24,
                    children: {
                      index: false,
                      indexLabel: "序号",
                      align: 'center',
                      type: 'form',
                      headerAlign: 'left',
                      rowAdd: (done) => {
                        this.$message.success('新增回调');
                        done({
                          input: '默认值'
                        });
                      },
                      rowDel: (row, done) => {
                        this.$message.success('删除回调' + JSON.stringify(row));
                        done();
                      },
                      column: [
                        {
                          label: '校区名',
                          prop: "campusName",
                          type: 'input',
                          span: 10,
                        },
                        {
                          width: 200,
                          label: '编码',
                          prop: "campusCode",
                          type: 'input',
                          span: 5
                        },]

                    }
                  }
                ]
          },
          {
            icon: 'el-icon-info',
            label: 'SETP3:考场设置',
            prop: 'group1',
            column:
                [
                  {
                    label: '总人数',
                    prop: 'totalNum',
                    type: 'title',
                  },
                  {
                    labelWidth: 120,
                    label: '考场容量设置',
                    prop: 'examHalls',
                    type: 'dynamic',
                    span: 24,
                    children: {
                      index: false,
                      indexLabel: "序号",
                      align: 'center',
                      type: 'form',
                      headerAlign: 'left',
                      rowAdd: (done) => {
                        // this.$message.success('新增回调');
                        done({
                          open: true
                        });
                      },
                      rowDel: (row, done) => {
                        this.$message.success('删除回调' + JSON.stringify(row));
                        done();
                      },
                      column: [
                        {
                          label: '校区',
                          prop: "campus",
                          type: 'select',
                          span: 6,
                          dicType: 'campus',
                          dicData: []
                        },
                        {
                          label: '考场编码',
                          prop: "examHallKey",
                          type: 'input',
                          span: 6,
                        },
                        {
                          label: '考场名',
                          prop: "examHallName",
                          type: 'input',
                          span: 6,
                        },
                        {
                          width: 200,
                          label: '容量',
                          prop: "capacity",
                          type: 'number',
                          span: 6
                        },
                        {
                          width: 200,
                          label: '是否可用',
                          prop: "open",
                          type: 'switch',
                          span: 6
                        },
                        {
                          width: 200,
                          label: '支持学科',
                          prop: "subjects",
                          type: 'select',
                          multiple: true,
                          dicData: [],
                          span: 6
                        },
                      ]

                    }
                  }
                ]
          },

          {
            icon: 'el-icon-info',
            label: 'SETP4:时间配置',
            prop: 'group1',
            column: [
              {
                label: '',
                prop: 'globalTimeSettingTips',
                type: 'title',
                labelWidth: 200,
                row: true,
                styles: {
                  align: 'center',
                }

              },
              {
                label: "起止时间",
                prop: 'examTimeRange',
                type: 'timerange',
                format: 'HH:mm',
                row: true,
                span: 24,
                valueFormat: 'HH:mm',
                startPlaceholder: '时间开始范围自定义',
                endPlaceholder: '时间结束范围自定义',
                tip: "每一天开始考试的时间和考试结束的时间 用于时间自动分配"
              },
              {
                label: "考试间隔",
                prop: "examTimeSpan",
                type: "time",
                format: 'HH小时:mm分钟',
                valueFormat: 'HH:mm',
                row: true,
                span: 24,
              },
              {
                label: "考试时长",
                prop: "examTimeStep",
                valueFormat: 'HH:mm',
                type: "time",
                format: 'HH小时:mm分钟',
                row: true,
                span: 24,
              },
              {
                label: "排除时间",
                prop: 'excludeTimeRanges',
                type: 'dynamic',
                row: true,
                span: 24,
                children: {
                  column: [
                    {
                      label: "排除时间",
                      prop: 'excludeTimeRange',
                      type: 'timerange',
                      format: 'HH:mm',
                      row: true,
                      span: 24,
                      valueFormat: 'HH:mm',
                      startPlaceholder: '时间开始范围自定义',
                      endPlaceholder: '时间结束范围自定义',
                      tip: "每一天开始考试的时间和考试结束的时间 用于时间自动分配",
                    }],
                }
              },
              {
                label: '',
                prop: 'subjectSettingTips',
                type: 'title',
                labelWidth: 200,
                row: true,
                styles: {
                  align: 'center',
                }

              },
              {
                label: '',
                prop: 'subjectSetting',
                type: 'dynamic',
                span: 24,
                row: true,
                children: {
                  index: false,
                  indexLabel: "序号",
                  align: 'center',
                  type: 'form',
                  headerAlign: 'left',
                  rowAdd: (done) => {
                    this.$message.success('新增回调');
                    done({
                      input: '默认值'
                    });
                  },
                  rowDel: (row, done) => {
                    this.$message.success('删除回调' + JSON.stringify(row));
                    done();
                  },
                  column: [
                    {
                      width: 200,
                      label: '学科',
                      prop: "subjects",
                      type: 'select',
                      dicData: [],
                      span: 6
                    },
                    {
                      row: true,
                      span: 24,
                      label: "考试日期",
                      type: "dates",
                      prop: 'examDates',
                      format: 'YYYY-MM-DD',
                      valueFormat: 'YYYY-MM-DD',
                      startPlaceholder: '时间日期开始范围自定义',
                      endPlaceholder: '时间日期结束范围自定义',
                    },
                    {
                      label: "起止时间",
                      prop: 'examTimeRange',
                      type: 'timerange',
                      format: 'HH:mm',
                      row: true,
                      span: 24,
                      valueFormat: 'HH:mm',
                      startPlaceholder: '时间开始范围自定义',
                      endPlaceholder: '时间结束范围自定义',
                      tip: "每一天开始考试的时间和考试结束的时间 用于时间自动分配"
                    },
                    {
                      label: "考试间隔",
                      prop: "examTimeSpan",
                      type: "time",
                      format: 'HH小时:mm分钟',
                      valueFormat: 'HH:mm',
                      row: true,
                      span: 24,
                    },
                    {
                      label: "考试时长",
                      prop: "examTimeStep",
                      valueFormat: 'HH:mm',
                      type: "time",
                      format: 'HH小时:mm分钟',
                      row: true,
                      span: 24,
                    },
                    {
                      label: "排除时间",
                      prop: 'excludeTimeRanges',
                      type: 'dynamic',
                      row: true,
                      span: 24,
                      children: {
                        column: [
                          {
                            label: "排除时间",
                            prop: 'excludeTimeRange',
                            type: 'timerange',
                            format: 'HH:mm',
                            row: true,
                            span: 24,
                            valueFormat: 'HH:mm',
                            startPlaceholder: '时间开始范围自定义',
                            endPlaceholder: '时间结束范围自定义',
                            tip: "每一天开始考试的时间和考试结束的时间 用于时间自动分配",
                          }],
                      }
                    },
                  ]
                }
              },
            ]
          },
          {
            icon: 'el-icon-info',
            label: 'SETP5:导入配置',
            prop: 'importSetting',
            column:
                [

                  {
                    labelWidth: 120,
                    label: '列定义',
                    prop: 'columnDefines',
                    type: 'dynamic',
                    span: 24,
                    children: {
                      index: false,
                      indexLabel: "序号",
                      align: 'center',
                      type: 'form',
                      headerAlign: 'left',
                      rowAdd: (done) => {
                        this.$message.success('新增回调');
                        done({
                          input: '默认值'
                        });
                      },
                      rowDel: (row, done) => {
                        this.$message.success('删除回调' + JSON.stringify(row));
                        done();
                      },
                      column: [
                        {
                          label: '名称',
                          prop: "label",
                          type: 'input',
                          span: 6,
                          dicData: []
                        },
                        {
                          label: '编码',
                          prop: "prop",
                          type: 'input',
                          span: 6,
                        },
                        {
                          label: '类型',
                          prop: "type",
                          type: 'select',
                          span: 6,
                          // control: (val, form) => {
                          //   console.log(val, form)
                          //   if (val === 'select') {
                          //     return {
                          //       dicData: {
                          //         display: true
                          //       }
                          //     }
                          //   } else {
                          //     return {}
                          //   }
                          // },
                          dicData: [
                            {
                              label: '文本',
                              value: "input"
                            }, {
                              label: '数值',
                              value: "number"
                            },
                            {
                              label: '字典',
                              value: "select"
                            },
                            {
                              label: '模板',
                              value: "template"
                            },
                            {
                              label: '时间',
                              value: "datetime"
                            },
                          ]
                        },
                        {
                          width: 200,
                          label: '模板文本',
                          prop: "source",
                          type: 'input',
                          span: 6,
                        },
                        {
                          width: 200,
                          label: '字典',
                          prop: "dicType",
                          type: 'select',
                          span: 6,
                          dicData: [
                            {
                              label: "学科",
                              value: 'subjects'
                            },
                            {
                              label: "校区",
                              value: 'campus'
                            }
                          ],
                        },
                        {
                          width: 200,
                          label: '时间格式化',
                          prop: "pattern",
                          type: 'input',
                          span: 6,
                        },

                      ]

                    }
                  },
                  {
                    labelWidth: 120,
                    label: '列映射',
                    prop: 'columnsMap',
                    type: 'dynamic',
                    span: 24,
                    children: {
                      index: false,
                      indexLabel: "序号",
                      align: 'center',
                      type: 'form',
                      headerAlign: 'left',
                      rowAdd: (done) => {
                        this.$message.success('新增回调');
                        done({
                          input: '默认值'
                        });
                      },
                      rowDel: (row, done) => {
                        this.$message.success('删除回调' + JSON.stringify(row));
                        done();
                      },
                      column: [
                        {
                          label: '系统字段',
                          prop: "type",
                          type: 'select',
                          span: 6,
                          dicType: "exportColumn",
                        },
                        {
                          label: '原始字段',
                          prop: "label",
                          type: 'array',
                          span: 6,
                        },
                      ]
                    }
                  }
                ]
          },
          {
            icon: 'el-icon-info',
            label: 'SETP6:导出配置',
            prop: 'group1',
            column: [
              {
                label: '文件名',
                prop: 'fileName',
                type: 'input',
                row: true
              },
              {
                label: '导出列',
                prop: 'exportColumn',
                type: 'dynamic',
                span: 24,
                row: true,
                children: {
                  index: false,
                  indexLabel: "序号",
                  align: 'center',
                  type: 'form',
                  headerAlign: 'left',
                  rowAdd: (done) => {
                    this.$message.success('新增回调');
                    done({
                      input: '默认值'
                    });
                  },
                  rowDel: (row, done) => {
                    this.$message.success('删除回调' + JSON.stringify(row));
                    done();
                  },
                  column: [
                    {
                      label: '系统字段',
                      prop: "exportColumnKey",
                      type: 'select',
                      dicType: 'exportColumn',
                      span: 12,
                      dicData: []
                    },
                  ]
                }
              },
            ]
          },
        ],
        column: []
      },

    }
  },
  created() {
    this.initFormData()
    this.updateDicData(this.option.group, appConfig.dicts)
  },

  methods: {
    initFormData() {
      var data = this.preProcessAppConfig(appConfig);
      this.formData = {
        ...data,
        title: "配置",
        globalTimeSettingTips: '全局时间配置',
        subjectSettingTips: '科目时间配置',
        totalNum: mainPageStore.data.length,
        // ...appConfig

      }
    },
    submit(form, done) {
      // this.$message.success(JSON.stringify(form));

      let appConfig = this.postProcessAppConfig(form)

      console.log(appConfig)
      this.updateDicData(this.option.group, appConfig.dicts)

      this.$message.success("保存成功")
      done()

    },
    //将应用配置转化成表单
    preProcessAppConfig(appConfig) {
      let data = {}

      data.subjects = this.convertSubject(appConfig.dicts.subjects)

      data.campus = this.convertCampus(appConfig.dicts.campus)

      data.examHalls = this.convertExamHalls(appConfig.examHalls)

      //转换全局时间配置
      _.merge(data, appConfig.arrangeConfig.globalTimeSetting);

      //转换学科时间配置
      data.subjectSetting = this.convertSubjectTimeSetting(appConfig.arrangeConfig.subjectSetting)

      data.columnDefines = this.convertColumnDefines(appConfig.columnDefines)

      data.columnsMap = this.convertColumnsMap(appConfig.columnsMap)

      //合并导出配置
      _.merge(data, this.convertExportConfig(appConfig.exportConfig));


      console.log('data.columnDefines', data.columnDefines)

      return data;
    },

    convertSubject(subjectDicData) {
      //转换学科
      return subjectDicData.map(item => {
        return {
          subjectName: item.label,
          subjectCode: item.value
        }
      })
    },

    convertCampus(subjectDicData) {
      //转换学科
      return subjectDicData.map(item => {
        return {
          campusName: item.label,
          campusCode: item.value
        }
      })
    },
    convertExamHalls(examHalls) {
      return examHalls.map(item => {
        item.examHallKey = item.code;
        item.examHallName = item.name;
        return item
      })
    },
    convertAppConfigExamHalls(formData, appConfig) {
      appConfig['examHalls'] = formData.examHalls.map(item => {
        item.code = item.examHallKey;
        item.name = item.examHallName;
        return item
      })
    },
    convertSubjectTimeSetting(subjectTimeSetting) {
      let data = []
      for (let subjectTimeSettingKey in subjectTimeSetting) {
        data.push({
          subjects: subjectTimeSettingKey,
          ...subjectTimeSetting[subjectTimeSettingKey]
        })
      }
      return data;
    },
    convertAppConfigSubjectTimeSetting(formData, appConfig) {
      let arrangeConfig = {
        subjectSetting: {}
      }
      for (let i = 0; i < formData.subjectSetting.length; i++) {
        let item = formData.subjectSetting[i]
        let subjects = item.subjects;
        arrangeConfig.subjectSetting[subjects] = item
      }

      if (!appConfig['arrangeConfig']) {
        appConfig['arrangeConfig'] = arrangeConfig
      } else {
        appConfig['arrangeConfig']['subjectSetting'] = arrangeConfig['subjectSetting']
      }
    },

    convertAppConfigGlobalTimeSetting(formData, appConfig) {
      let arrangeConfig = {
        globalTimeSetting: {}
      }
      arrangeConfig['globalTimeSetting'] =
          {
            //每场考试时间
            examTimeStep: formData.examTimeStep,
            //两场考试时间间隔
            examTimeSpan: formData.examTimeSpan,


            //考试的时间范围
            examTimeRange: formData.examTimeRange,
            excludeTimeRanges: formData.excludeTimeRanges,
          }

      if (!appConfig['arrangeConfig']) {
        appConfig['arrangeConfig'] = arrangeConfig
      } else {
        appConfig['arrangeConfig']['globalTimeSetting'] = arrangeConfig['globalTimeSetting']
      }
    },
    convertColumnDefines(columnDefines) {
      let data = []
      for (let prop in columnDefines) {
        data.push({
          ...columnDefines[prop]

        })
      }
      return data;
    },
    convertAppColumnDefines(formData, appConfig) {
      let columnDefines = formData.columnDefines;
      let convertColumnDefines = {}
      for (let i = 0; i < columnDefines.length; i++) {
        let item = columnDefines[i]
        convertColumnDefines[item.prop] = {
          label: item['label'],
          prop: item['prop'],
          type: item['type'],
          search: item['search'],
          source: item['source'],
          pattern: item['pattern'],
          dicData: item.dicType ? typeof item.dicType === 'string' ? [item.dicType] : item.dicType : null,
          dicType: item.dicType
        }

        if (!convertColumnDefines[item.prop].dicData) {
          delete convertColumnDefines[item.prop].dicData
        }
      }
      console.log('convertColumnDefines', convertColumnDefines)
      appConfig.columnDefines = convertColumnDefines
    },

    convertColumnsMap(columnsMap) {
      let data = []
      for (let prop in columnsMap) {
        data.push({
          type: prop,
          label: columnsMap[prop]
        })
      }

      console.log('convertColumnsMap', data)
      return data;
    },


    convertAppConfigColumnsMap(formData, appConfig) {
      let data = {}


      for (let i = 0; i < formData.columnsMap.length; i++) {
        let item = formData.columnsMap[i]
        data[item.type] = item.label;
      }

      appConfig.columnsMap = data
    },
    convertExportConfig(exportConfig) {

      if (exportConfig.exportColumn) {
        exportConfig.exportColumn = exportConfig.exportColumn.map(item => {

          if (typeof item === 'string') {
            let exportColumnKey = item
            return {
              exportColumnKey: exportColumnKey,
            }
          }
          return item;
        })
      }
      console.log(exportConfig)
      return exportConfig
    },

    convertAppConfigExportConfig(formData, appConfig) {
      appConfig.exportConfig = {
        fileName: formData.fileName,
        //导出列
        exportColumn: formData.exportColumn.map(item => item.exportColumnKey)
      }

    },

    //更新字典
    updateDicData(column, dicData) {
      console.log('updateDicData', column, dicData)
      for (let i = 0; i < column.length; i++) {
        let item = column[i];
        if (item.type === 'select') {
          if (dicData[item.dicType]) {
            console.log('item.dicType', item.dicType);

            item.dicData = dicData[item.dicType]
          } else if (dicData[item.prop]) {
            console.log('item.prop', item.prop);
            item.dicData = dicData[item.prop];
            console.log(item.dicData)
          }
        } else if (isValidArray(item.column)) {
          this.updateDicData(item.column, dicData)
        } else if (item.type === 'dynamic') {
          this.updateDicData(item.children.column, dicData)
        }
      }
    },
    //将表单转化成应用配置
    postProcessAppConfig(formData) {
      // console.log('formData', formData)
      let appConfig = {}

      //转换列定义
      this.convertAppColumnDefines(formData, appConfig)


      //转换字典
      this.convertAppConfigDictData(formData, appConfig)


      //转换考场
      this.convertAppConfigExamHalls(formData, appConfig)


      //转换科目考场时间安排
      this.convertAppConfigSubjectTimeSetting(formData, appConfig)

      //转换全局时间安排
      this.convertAppConfigGlobalTimeSetting(formData, appConfig)

      //转换导出列配置
      this.convertAppConfigExportConfig(formData, appConfig)

      //转换导出列映射
      this.convertAppConfigColumnsMap(formData, appConfig)
      // _.merge(appConfig, formData)
      console.log("保存后的appConfig", appConfig)

      SessionUtils.set(TEST_ARRANGE_APP_CONFIG_KEY, appConfig)

      processAppConfig(appConfig)

      return appConfig;

    },
    convertAppConfigDictData(formData, appConfig) {
      appConfig.dicts = {
        subjects: formData.subjects.map(item => {
          return {
            label: item.subjectName,
            value: item.subjectCode
          }
        }),
        campus: formData.campus.map(item => {
          return {
            label: item.campusName,
            value: item.campusCode
          }
        }),
      }
      //处理导出列的字典
      processExportColumnDicData(appConfig)


    },
    //处理应用配置
    processAppConfig(appConfig) {
      appConfig.columns = processColumn(appConfig.columnsMap, appConfig.columnDefines)
      appConfig.columnNamePropMap = processNamePropNameMap(appConfig.columnsMap)
      //加载考场的字典
      processExamHallDict()
    }


  }
}
</script>